package com.ruoyi.api.rabbitMQ2;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ywh
 * @date 2021/5/26
 * @desc
 */

@Configuration
public class DelayQueueConfiguration {

    public static String DELAY_EXCHANGE = "ueEdu_delay_exchange";
    public static String DELAY_EXCHANGE_KEY = "ueEdu_delay_routing_key";
    public static int time = 10000;
    /*
    1，创建临时队列和临时交换机，临时队列设置超时时间，过期后投放到死信交换机
    2，将消息通过临时交换机绑定到临时队列
    3，死信队列（即业务处理队列）和死信交换机：死信交换机收到第1步的消息，并把消息投档到死信队列
    4，消息投递时直接投递到临时交换机和队列
     */

    /*
    临时队列
     */
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable("ueEdu_delay_queue")
                //过期之后，消息投放的交换机
                .withArgument("x-dead-letter-exchange", DELAY_EXCHANGE)
                //指定的key
                .withArgument("x-dead-letter-routing-key", DELAY_EXCHANGE_KEY)
                //超时时间，单位ms
                .withArgument("x-message-ttl", time)
                .build();
    }

    /*
     * 临时队列交换机，用于投递消息
     */
    @Bean
    public DirectExchange delayTtlExchange() {

        return new DirectExchange("ueEdu_delay_ttl_exchange", true, false);
    }

    /*
     * 临时队列和交换机绑定
     */
    @Bean
    public Binding delayTtlBinding() {

        return BindingBuilder.bind(delayQueue()).to(delayTtlExchange()).with("ueEdu_delay_ttl_key");
    }


    /*
    业务队列（死信队列）
     */
    @Bean
    public Queue deadQueue() {
        return new Queue("ueEdu_dead_process_queue", true);
    }


    /*
    死信交换机：
    临时队列消息过期，会被投放到这个交换机
     */
    @Bean
    public DirectExchange delayExchange() {
        return new DirectExchange(DELAY_EXCHANGE, true, false);
    }

    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(deadQueue()).to(delayExchange()).with(DELAY_EXCHANGE_KEY);
    }

}




